<template>
  <div>
    <el-form :inline="true" :model="buyBackForm" ref="buyBackForm">
      <div class="pc-page-header">
        <el-form-item prop="arNo">
          <el-input v-model="buyBackForm.arNo" clearable class="pc-input3-col5" placeholder="输入申请编号"></el-input>
        </el-form-item>
        <el-form-item prop="arType">
          <el-select v-model="buyBackForm.arType" clearable placeholder="选择申请类型" class="pc-input3-col5">
            <el-option v-for="item in tradeTypeOption" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="arStatus">
          <el-select v-model="buyBackForm.arStatus" clearable placeholder="选择申请状态" class="pc-input3-col5">
            <el-option v-for="item in statusOption" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="storageName">
          <el-input v-model="buyBackForm.storageName" clearable class="pc-input3-col5"
                    placeholder="输入入库仓库"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="queryDataFn">搜索</el-button>
          <el-button type="primary" @click="refresh('buyBackForm', true)">刷新</el-button>
        </el-form-item>
        <el-button v-permission="['wms:trade:buyback:applysell']" size="small" type="primary" @click="toAppSale">申请出售</el-button>
        <el-button v-permission="['wms:trade:buyback:applybuyback']" size="small" type="primary" @click="toAppBuy">申请回购</el-button>
        <!--<el-button @click="showMore()">{{showMoreText}}</el-button>-->
      </div>
    </el-form>
    <egrid border
           class="page-list"
           :data="tableData"
           :columns="columns"
           :columns-schema="columnsSchema"
           :columns-props="columnsProps"
           :columns-handler="columnsHandler">
    </egrid>
    <div class="pc-pagination-panel">
      <pc-pagination ref="pcPagination" :url="pageUrl.queryList" :queryData="buyBackForm" @on-query="queryCallBackFn">
      </pc-pagination>
    </div>

    <!--申请出售页面-->
    <pc-dialog :is-show="isShowAppSale" title='申请出售' @on-close="isShowAppSale = false">
      <div>
        <app-sale @closeRefresh="closeRefresh"></app-sale>
      </div>
    </pc-dialog>

    <!--申请回购页面-->
    <pc-dialog :is-show="isShowAppBuy" title='申请回购' @on-close="isShowAppBuy = false">
      <div>
        <app-buy @closeRefresh="closeRefresh"></app-buy>
      </div>
    </pc-dialog>


    <pc-dialog :is-show="isShowAuditDialog" title='审核出售' @on-close="isShowAuditDialog = false">
      <audit-sell :id="arId" @closeRefresh="closeRefresh"></audit-sell>
    </pc-dialog>
    <pc-dialog :is-show="isShowAuditBuyBackDialog" title='审核回购' @on-close="isShowAuditBuyBackDialog = false">
      <audit-buy-back :id="arId" @closeRefresh="closeRefresh"></audit-buy-back>
    </pc-dialog>

    <!--确认出售/ 出售详情页面-->
    <pc-dialog :is-show="isShowTradeSale" :title="tradeSaleTitle" @on-close="isShowTradeSale = false">
      <div>
        <tradeSale :tradeData="TradeSaleData"  @closeRefresh="closeRefresh"></tradeSale>
      </div>
    </pc-dialog>
    <!--确认回购/确认回购详情页面-->
    <pc-dialog :is-show="isShowTradeBuy" :title="tradeBuyTitle" @on-close="isShowTradeBuy = false">
      <div>
        <tradeBuy :tradeData="TradeBuyData"  @closeRefresh="closeRefresh"></tradeBuy>
      </div>
    </pc-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
  import PcPagination from 'components/form/pagination';
  import PcButton from 'components/form/button';
  import PcDialog from 'components/dialog';
  import { enums } from 'src/utils/settings/index';
  import AppSale from 'src/views/wms/trade/buy-back/appSale';
  import AppBuy from 'src/views/wms/trade/buy-back/appBuy';
  import TradeSale from 'src/views/wms/trade/buy-back/tradeSale';
  import TradeBuy from 'src/views/wms/trade/buy-back/tradeBuy';
  import AuditSell from 'src/views/wms/trade/buy-back/auditSell';
  import AuditBuyBack from 'src/views/wms/trade/buy-back/auditBuyBack';
  let that;
  // 操作按钮
  var Btn = {
    template: `<div style="display:flex; width: 100%;flex-wrap: wrap">
        <el-button v-if="showAuditSell && hasPermission('wms:trade:buyback:auditsell')" type="danger" plain @click="auditShell(row)">审核出售</el-button>
        <el-button v-if="showAuditBuyBack && hasPermission('wms:trade:buyback:auditbuyback')" type="danger" plain @click="auditBuyBack(row)">审核回购</el-button>
        <el-button v-if="showConfirmSell && hasPermission('wms:trade:buyback:confirmsell')" type="danger" plain @click="toTradeSale(row)">确认出售</el-button>
        <el-button v-if="showConfirmBuyBack && hasPermission('wms:trade:buyback:confirmbuyback')" type="danger" plain @click="toTradeBuy(row)">确认回购</el-button>
        <el-button v-permission="['wms:trade:buyback:detail']" type="primary" plain @click="toTradeDetail(row)">详情</el-button>
      </div>`,
    props: ['row'],
    data() {
      return {
        roleType: null // 角色类型
      };
    },
    created () {
      this.roleType = parseInt(this.$store.getters.getRoleId);
    },
    computed: {
      showHandle() {
        return this.row.arStatus;
      },
      // 是否显示审核出售按钮
      showAuditSell() {
        return this.row.arStatus === enums.BUY_BACK_STATUS.SELL_FOR_AUDIT;
      },
      // 是否显示确认出售按钮
      showConfirmSell() {
        return this.row.arStatus === enums.BUY_BACK_STATUS.SELL_FOR_CONFIRM;
      },
      // 是否显示确认回购按钮
      showConfirmBuyBack() {
        return this.row.arStatus === enums.BUY_BACK_STATUS.BACK_FOR_CONFIRM;
      },
      // 是否显示审核回购按钮
      showAuditBuyBack() {
        return this.row.arStatus === enums.BUY_BACK_STATUS.BACK_FOR_AUDIT;
      },
      // 是否显示审核回购按钮
      showDetail() {
//        console.log('this.row: ' + JSON.stringify(this.row) + ' roleType: ' + this.roleType);
        // 判断如果是资金型货主且约定回购状态不是待审核时则显示详情按钮
        let showDetail = (this.row.arStatus !== enums.BUY_BACK_STATUS.SELL_FOR_AUDIT &&
          this.row.arStatus !== enums.BUY_BACK_STATUS.BACK_FOR_AUDIT);
        // 判断如果是货主企业且约定回购状态不是待确认时则显示详情按钮
        showDetail = showDetail || (this.roleType === enums.ROLE_TYPE.OWNER &&
          (this.row.arStatus !== enums.BUY_BACK_STATUS.SELL_FOR_CONFIRM &&
          this.row.arStatus !== enums.BUY_BACK_STATUS.BACK_FOR_CONFIRM));
        // 判断如果是admin且约定回购状态不是待审核/待确认时则显示详情按钮
        showDetail = showDetail || (this.roleType === enums.ROLE_TYPE.ADMIN &&
          (this.row.arStatus !== enums.BUY_BACK_STATUS.SELL_FOR_CONFIRM &&
          this.row.arStatus !== enums.BUY_BACK_STATUS.BACK_FOR_CONFIRM &&
          this.row.arStatus !== enums.BUY_BACK_STATUS.SELL_FOR_AUDIT &&
          this.row.arStatus !== enums.BUY_BACK_STATUS.BACK_FOR_AUDIT));
        return showDetail;
      }
    },
    methods: {
      // 审核出售
      auditShell (val) {
//        console.log('handle order------row: ' + JSON.stringify(val));
        this.$emit('audit-sell', val);
      },
      // 审核回购
      auditBuyBack (val) {
        this.$emit('audit-buy-back', val);
      },
      // 确认出售
      toTradeSale (val) {
        this.$emit('to-trade-sale', val);
      },
      // 确认回购
      toTradeBuy (val) {
        this.$emit('to-trade-buy', val);
      },
      // 回购 出售  详情
      toTradeDetail (val) {
        this.$emit('to-trade-detail', val);
      },
      viewDetail(val) {
        this.$emit('view-detail', val);
      }
    }
  };
  export default {
    data () {
      return {
        isshowMore: false,
        isShowAuditDialog: false, // 判断是否显示审核出售页面
        isShowAuditBuyBackDialog: false, // 判断是否显示审核回购页面
        isShowAppSale: false, // 申请出售页面
        isShowTradeSale: false, // 确认 出售/回购/详情,
        isShowAppBuy: false, // 申请回购页面
        isShowTradeBuy: false, // 确认 出售/回购/详情,
        showDetailDialog: false, // 判断是否显示详情页面
        tradeSaleTitle: '', // 确认 出售/回购/详情 顶部title;
        tradeBuyTitle: '',
        tradeSaleBuy: '',
        showMoreText: '更多',
        roleType: 0, // 1超级管理员 2云仓 3 货主企业, 4 资金型货主
        tradeData: {},
        TradeSaleData: {},
        TradeBuyData: {},
        buyBackForm: {
          arNo: null,
          arType: null,
          arStatus: null,
          storageId: null,
          storageName: null
        },
        tableData: [],
        baseColumns: [
          {
            label: '申请编号',
            prop: 'arNo'
          },
          {
            label: '申请时间',
            prop: 'createdTime'
          },
          {
            label: '申请类型',
            prop: 'arTypeDesc'
          },
          {
            label: '申请状态',
            prop: 'arStatusDesc'
          },
          {
            label: '保管人',
            prop: 'storageCompanyName'
          },
          {
            label: '保管仓',
            prop: 'storageName'
          },
          {
            label: '货物名称',
            prop: 'goodsNames'
          },
          {
            label: '操作',
            minWidth: 192,
            fixed: 'right',
            component: Btn, // 'el-button'
            listeners: {
              'audit-sell' (data) {
                that.auditSell(data);
              },
              'audit-buy-back' (data) {
                that.auditBuyBack(data);
              },
              'to-trade-sale' (data) {
                that.toTradeSale(data);
              },
              'to-trade-buy' (data) {
                that.toTradeBuy(data);
              },
              'to-trade-detail' (data) {
                that.toTradeDetail(data);
              },
              'view-detail' (data) {
                that.showDetailDialog = true;
              }
            },
            propsHandler: function ({ row, col, column }) {
              return {row, col, column};
            }
          }
        ],
        columnsSchema: {
          '货物名称': {
            minWidth: 240
            // 定义表格列如何渲染, 用showOverflowTooltip: true代替
//            component: LongContentCol // 列内容过长内容展示组件（设置超出部分隐藏，鼠标移上去显示全部）
          }
        },
        // columnsProps 用于定义所有 columns 公共的属性，
        // 这里属性可以参考这里： http://element.eleme.io/#/zh-CN/component/table#table-column-attributes
        columnsProps: {
          height: 40,
          minWidth: 150,
          showOverflowTooltip: true
        },
        // 约定回购类型
        tradeTypeOption: [
          {
            value: 1,
            label: '仓单出售'
          },
          {
            value: 2,
            label: '仓单回购'
          }
        ],
        // 约定回购状态
        statusOption: [
          {
            value: 1,
            label: '出售待审核'
          },
          {
            value: 2,
            label: '出售待确认'
          },
          {
            value: 3,
            label: '出售审核不通过'
          },
          {
            value: 4,
            label: '出售已成交'
          },
          {
            value: 5,
            label: '出售确认不通过'
          },
          {
            value: 6,
            label: '回购待审核'
          },
          {
            value: 7,
            label: '回购待确认'
          },
          {
            value: 8,
            label: '回购审核不通过'
          },
          {
            value: 9,
            label: '回购已成交'
          },
          {
            value: 10,
            label: '回购确认不通过'
          }
        ],
        emptyText: '',
        currentPage: 1,
        pageUrl: {
          queryList: '/maliwms/ar/getArPageList' // 列表数据接口地址
        },
        arId: '', // 约定回购ID
        detailTitle: '查看详情' // 详情页title
      };
    },
    components: {
      PcPagination, PcButton, PcDialog, AppSale, TradeSale, TradeBuy, AppBuy, AuditSell, AuditBuyBack
    },
    created () {
      this.roleType = parseInt(this.$store.getters.getRoleId);
      console.log(this.roleType);
      that = this;
    },
    computed: {
      // 根据角色类型计算需要展示的列数据
      columns() {
        let columns = [].concat(this.baseColumns.slice(0, 4));
        let affterColumns = [].concat(this.baseColumns.slice(4, this.baseColumns.length));
        let diffColumns = null;
        // admin或者云仓
        if (this.roleType === 1 || this.roleType === 2) {
          diffColumns = [
            {
              label: '出售方',
              prop: 'sellerName'
            },
            {
              label: '交易对象',
              prop: 'buyerName'
            }
          ];
        }
        // 货主企业
        if (this.roleType === 3) {
          diffColumns = [
            {
              label: '交易对象',
              prop: 'buyerName'
            }
          ];
        }
        // 资金型货主
        if (this.roleType === 4) {
          diffColumns = [
            {
              label: '出售方',
              prop: 'sellerName'
            }
          ];
        }
        columns = columns.concat(diffColumns);
        columns = columns.concat(affterColumns);
//        columns.splice(4, 0, diffColumns);
//        console.log('columns: ' + JSON.stringify(columns));
        return columns;
      }
    },
    methods: {
      // 表头样式
      getHeaderStyle({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return 'background: #f5f5f5; height: 50px';
        } else {
          return '';
        }
      },
      showMore () {
        this.isshowMore = !this.isshowMore;
        if (this.isshowMore) {
          this.showMoreText = '收起';
        } else {
          this.showMoreText = '更多';
        }
      },
      // 请求订单管理列表接口成功回调函数
      queryCallBackFn (res) {
        this.tableData = res.result.list;
//        console.log('data: ' + JSON.stringify(this.tableData));
      },
      // 获取订单管理列表数据
      queryDataFn (isRefresh) {
        this.$refs.pcPagination.queryListWithPageFn(isRefresh);
      },
      // 刷新订单管理列表数据
      refresh (formName, isRefresh) {
        this.$refs[formName].resetFields();
        this.queryDataFn(isRefresh);
      },
      columnsHandler() {

      },
      // 审核出售
      auditSell (val) {
        this.arId = val.id;
        this.isShowAuditDialog = true;
      },
      // 审核回购
      auditBuyBack (val) {
        this.arId = val.id;
        this.isShowAuditBuyBackDialog = true;
      },
      // 申请出售
      toAppSale () {
        this.isShowAppSale = true;
        console.log('申请出售');
      },
      toTradeSale (row) {
        this.tradeSaleTitle = '确认出售';
        this.getTradeSaleData(row, 0);
        if (this.TradeSaleData) {
          this.isShowTradeSale = true;
        }
      },
      // 获取约定回购 确认回购页面展示信息
      toTradeBuy (row) {
       // let arStatus = row.arStatus;
//        if (arStatus === 6 || arStatus === 8 || arStatus === 9 || arStatus === 10) {
//          // 查看回购详情
//          titleIndex = 1;
//          pageType = 1;
//        }
        this.tradeBuyTitle = '确认回购';
        this.getTradeBuyData(row, 0);
        if (this.TradeBuyData) {
          this.isShowTradeBuy = true;
        }
      },
      // 详情页面跳转
      toTradeDetail (row) {
        console.log('row');
        console.log(row);
        let saleArr = [1, 2, 3, 4, 5];
        let buyArr = [6, 7, 8, 9, 10];
        let arStatus = row.arStatus;
        // 申请出售
        if (this.isInArray(saleArr, arStatus)) {
          this.tradeSaleTitle = '查看出售详情';
          this.getTradeSaleData(row, 1);
          if (this.TradeSaleData) {
            this.isShowTradeSale = true;
          }
        }
        // 申请回购
        if (this.isInArray(buyArr, arStatus)) {
          this.tradeBuyTitle = '查看回购详情';
          this.getTradeBuyData(row, 1);
          if (this.TradeBuyData) {
            this.isShowTradeBuy = true;
          }
        }
      },
      isInArray (arr, value) {
        for (var i = 0; i < arr.length; i++) {
          if (value === arr[i]) {
            return true;
          }
        }
        return false;
      },
      // 申请回购
      toAppBuy () {
        console.log('申请回购');
        this.isShowAppBuy = true;
      },
      closeRefresh (page) {
        if (page === 'appSale') {
          this.isShowAppSale = false;
        }
        // appBuy
        if (page === 'appBuy') {
          this.isShowAppBuy = false;
        }
        if (page === 'page-tradeSale') {
          this.isShowTradeSale = false;
        }
        if (page === 'page-tradeBuy') {
          this.isShowTradeBuy = false;
        }
        this.isShowAuditDialog = false;
        this.isShowAuditBuyBackDialog = false;
        this.queryDataFn(false);
      },
      // 获取 确认回购 页面展示信息
      getTradeSaleData (row, pageType) {
        this.TradeSaleData = [];
        let that = this;
        that.ajax({
          url: '/maliwms/ar/getArDetailByArId?arId=' + row.id,
          type: 'GET',
          loading: true,
          success: (res) => {
            setTimeout(() => {
              that.$pcNProgress.done();
            }, 300);
            if (res.code === 200) {
              this.TradeSaleData = res.result;
              this.TradeSaleData.pageType = pageType;
              console.log(' this.TradeSaleData');
              console.log(this.TradeSaleData);
            }
          }
        });
      },
      // 获取 确认回购 页面展示信息
      getTradeBuyData (row, pageType) {
        this.TradeBuyData = [];
        let that = this;
        that.ajax({
          url: '/maliwms/ar/getArDetailByArId?arId=' + row.id,
          type: 'GET',
          loading: true,
          success: (res) => {
            setTimeout(() => {
              that.$pcNProgress.done();
            }, 300);
            if (res.code === 200) {
              this.TradeBuyData = res.result;
              this.TradeBuyData.pageType = pageType;
              console.log('this.TradeBuyData');
              console.log(this.TradeBuyData);
            }
          }
        });
      }
    }
  };
</script>
